<template>
  <div>
    <el-container>
      <!--<el-header></el-header>-->
      <el-main>
        <el-row>
          <el-col :span="15">
            <el-button type="primary" @click="newuser">新增用户</el-button></el-col>
          <el-col :span="3">
            <el-select v-model="search_type" placeholder="搜索字段">
              <el-option label="ID" value="0"></el-option>
              <el-option label="手机" value="1"></el-option>
              <el-option label="邮箱" value="2"></el-option>
              <el-option label="昵称" value="3"></el-option>
              <el-option label="姓名" value="4"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="请输入搜索内容" v-model="searchuser" class="input-with-select" @input="userchange">
              <el-button @click="mysearch" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
        </el-row>
        <br>
        <el-table
          :data="tableData"
          border
          style="width: 100%">
          <!--<el-table-column-->
            <!--type="index"-->
            <!--width="80">-->
          <!--</el-table-column>-->
          <el-table-column
            prop="id"
            label="ID"
            width="100">
          </el-table-column>
          <el-table-column
            prop="phone"
            label="手机"
            width="120">
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱">
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="昵称">
          </el-table-column>
          <el-table-column
            prop="realname"
            label="真实姓名">
          </el-table-column>
          <el-table-column
            prop="gender"
            label="性别"
            width="80">
          </el-table-column>
          <el-table-column
            prop="birthday"
            label="生日"
            width="100">
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            width="100">
          </el-table-column>
          <el-table-column
            prop="group.chname"
            label="用户组"
            width="100">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-button @click="myeditor(scope.row)" type="text" size="small" >编辑</el-button>
              <!--disabled-->
              <template v-if="roles === 'superadmin' ">
                <el-button @click="mydelete(scope.row)" type="text" size="small">删除</el-button>
              </template>
              <template v-else>
                <el-button @click="mydelete(scope.row)" type="text" size="small" disabled>删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <el-row>
          <el-col :span="8"><p></p></el-col>
          <el-col :span="8">
            <el-pagination
              @current-change="currentChange"
              @size-change="sizeChange"
              background
              :page-sizes="[20, 40, 60, 100]"
              layout="sizes, prev, pager, next"
              :total="total"
              :page-size="page_size"
              :current-page="current_page"
              >
            </el-pagination>
          </el-col>
          <el-col :span="8"><p></p></el-col>
        </el-row>
        <el-dialog title="编辑用户信息" :visible.sync="dialogFormVisible" width="40%" center @close="dialogcolse">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :label-position="labelPosition">
            <template v-if="use === 1">
              <el-form-item label="手机" prop="phone">
                <el-input v-model="ruleForm.phone"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="ruleForm.email"></el-input>
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item label="手机or邮箱" prop="username">
                <el-input v-model="ruleForm.username" placeholder="请输入手机或邮箱"></el-input>
              </el-form-item>
            </template>
            <el-form-item label="密码" prop="password">
              <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="ruleForm.nickname"></el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="realname">
              <el-input v-model="ruleForm.realname"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select v-model="ruleForm.gender" placeholder="请选择">
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="2"></el-option>
                <el-option label="保密" value="3"></el-option>
                <el-option label="未设置" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
              <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.birthday"></el-date-picker>
            </el-form-item>
            <el-form-item label="用户状态" prop="status">
              <el-select v-model="ruleForm.status" placeholder="请选择">
                <el-option label="可用" value="1"></el-option>
                <el-option label="停用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户组" prop="group">
              <el-select v-model="ruleForm.group" placeholder="请选择" >
                <el-option
                  v-for="item in ruleForm.groups"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上传头像">
              <el-upload
                :action="upload_url"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handlesuccess"
                :before-remove="beforeRemove"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过6mb</div>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="resetForm('ruleForm')">取 消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
          </div>
        </el-dialog>


      </el-main>
      <el-footer></el-footer>
    </el-container>
  </div>
</template>

<script>
    import { getuser, getgroup, postuser, patchuser, deleteuser } from '@/api/course'
    import store from '../../store'
    let datetime = require("date-and-time")
    export default {
      name: 'usermanager',
      data() {
        return {
          timezoneOffset: '0',
          timeoffset: '00:00:00',
          tableData: [],
          dialogFormVisible: false,
          labelPosition: 'left',
          use: 0,
          ruleForm: {
            id: 0,
            phone: '',
            username: '',
            status: '1',
            birthday: '',
            email: '',
            nickname: '',
            realname: '',
            groups: [],
            group: 10,
            gender: '3',
            image_url: 'none',
            password: ''
          },
          rules: {},
          page_size: 20,
          total: 1717,
          current_page: 1,
          searchuser: '',
          upload_url: '',
          fileList: [],
          search_type: '0',
          roles: store.getters.roles[0]
        }
      },
      methods: {
        getuserinfo(page, keyword, page_size, search_type) {
          getuser(page, keyword, page_size, search_type).then(response => {
            const data = response.data
            var tmp_date
            // console.log(data)
            for (var key in data) {
              // tmp_date = new Date (data[key].birthday_ts * 1000)  // GMT time 
              // tmp_date = tmp_date.toJSON().replace('T',' ').replace('Z','') // 1990-01-01 00:00:00
              // data[key].birthday_s = new Date(tmp_date + this.timezoneOffset).toJSON().split('T')[0]
              // console.log(tmp_date)
              // data[key].birthday = tmp_date // 该时区的时间
              // console.log(tmp_date)
              if (data[key].status === 1) {
                data[key].status = '可用'
              } else {
                data[key].status = '停用'
              }
              switch (data[key].gender) {
                case 1:
                  data[key].gender = '男'
                  break
                case 2:
                  data[key].gender = '女'
                  break
                case 3:
                  data[key].gender = '保密'
                  break
                case 0:
                  data[key].gender = '未设置'
                  break
                default:
                  data[key].gender = '未设置'
                  break
              }
            }
            this.tableData = data
            this.total = response.data_count
          }).catch(error => {
            console.log(error)
          })
        },
        mysearch() {
          this.current_page = 1
          this.getuserinfo(this.current_page, this.searchuser, this.page_size, this.search_type)
        },
        userchange() {
          this.current_page = 1
          this.getuserinfo(this.current_page, this.searchuser, this.page_size, this.search_type)
        },
        getgroupinfo() {
          getgroup().then(response => {
            const data = response.data
            var new_data_list = []
            for (var key in data) {
              var new_data = {}
              new_data.value = data[key].id
              new_data.label = data[key].chname + "(" + data[key].name + ")"
              new_data_list.push(new_data)
            }
            this.ruleForm.groups = new_data_list
          }).catch(error => {
            console.log(error)
          })
        },
        clearFormdata() {
          this.ruleForm = {
            id: 0,
            phone: '',
            username: '',
            status: '1',
            birthday: '',
            email: '',
            nickname: '',
            realname: '',
            groups: [],
            group: 10,
            gender: '3',
            image_url: 'none',
            password: ''
          }
        },
        newuser() {
          // 这里放初始化的数据
          this.getgroupinfo()
          this.use = 0
          this.ruleForm.phone = ''
          this.ruleForm.email = ''
          this.ruleForm.nickname = ''
          this.ruleForm.realname = ''
          this.ruleForm.image_url = 'none'
          this.ruleForm.birthday = '1990-01-01' 
          // this.ruleForm.birthday = new Date('1990-01-01 00:00:00+0') // 默认生日为 UTC时间 1990-01-01 转换成当前时间
          // console.log(new Date('1990-01-01 00:00:00+0'))
          // this.ruleForm.birthday = newdate.toJSON().split('T')[0]
          // this.ruleForm.birthday = '1990-01-01 ' + this.timeoffset
          this.ruleForm.password = '123456'
          var ruleobj = {
            username: [
              { required: true, message: '请输入手机或邮箱', trigger: 'blur' }
            ],
            status: [
              { required: true, message: '请选择用户状态', trigger: 'change' }
            ],
            birthday: [
              { required: true, message: '请选择日期', trigger: 'change' }
            ],
            nickname: [
              { required: true, message: '请输入昵称', trigger: 'blur' }
            ],
            realname: [
              { required: true, message: '请输入真实姓名', trigger: 'blur' }
            ],
            group: [
              { required: true, message: '请选择用户组', trigger: 'blur' }
            ],
            gender: [
              { required: true, message: '请选择性别', trigger: 'blur' }
            ],
            password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
            image_url: [{ required: true, message: '请上传图片', trigger: 'blur' }]
          }
          this.rules = ruleobj
          this.dialogFormVisible = true
          console.log(this.rules)
        },
        myeditor(row) {
          this.getgroupinfo()
          this.use = 1
          var newobj = this.rules
          delete newobj.password
          delete newobj.image_url
          var ruleobj = {
            phone: [
              { required: true, message: '请输入手机号码', trigger: 'blur' }
            ],
            status: [
              { required: true, message: '请选择用户状态', trigger: 'change' }
            ],
            birthday: [
              { required: true, message: '请选择日期', trigger: 'change' }
            ],
            email: [
              { required: true, message: '请输入邮箱', trigger: 'blur' }
            ],
            nickname: [
              { required: true, message: '请输入昵称', trigger: 'blur' }
            ],
            realname: [
              { required: true, message: '请输入真实姓名', trigger: 'blur' }
            ],
            group: [
              { required: true, message: '请选择用户组', trigger: 'change' }
            ],
            gender: [
              { required: true, message: '请选择性别', trigger: 'change' }
            ],
            password: [{ required: false, message: '请输入用户密码', trigger: 'blur' }]
          }
          this.rules = ruleobj
          console.log(this.rules)
          this.ruleForm.id = row.id
          this.ruleForm.phone = row.phone
          this.ruleForm.email = row.email
          this.ruleForm.nickname = row.nickname
          this.ruleForm.realname = row.realname
          this.ruleForm.group = row.group.id
          this.ruleForm.password = ''
          this.ruleForm.image_url = ''
          this.ruleForm.birthday = row.birthday
          // var new_date_str = row.birthday.replace(/-/g, '/')
          // var newdate = new Date(row.birthday + " 00:00:00" + this.timezoneOffset)
          // console.log(newdate)
          // var newdate = new Date(row.birthday + " 00:00:00" + this.timezoneOffset) // 默认生日为 UTC时间 1990-01-01 转换成当前时间
          // this.ruleForm.birthday = newdate.toJSON().replace("T"," ").replace("Z","")
          // this.ruleForm.birthday = row.birthday + " 00:00:00"  // 坑，必须加时间才能正确显示日期，不然根据时区不同有可能会减一天
          // this.ruleForm.birthday = new Date(row.birthday + " " + this.timeoffset).toJSON().split('T')[0]
          // console.log(this.ruleForm.birthday)
          // this.ruleForm.birthday = new Date(row.birthday + "+0")
          // console.log(row.birthday)
          if (row.status === '可用') {
            this.ruleForm.status = '1'
          } else {
            this.ruleForm.status = '0'
          }
          switch (row.gender) {
            case '男':
              this.ruleForm.gender = '1'
              break
            case '女':
              this.ruleForm.gender = '2'
              break
            case '保密':
              this.ruleForm.gender = '3'
              break
            case '未设置':
              this.ruleForm.gender = '0'
              break
            default:
              this.ruleForm.gender = '0'
              break
          }
          this.dialogFormVisible = true
        },
        mydelete(row) {
          this.$confirm('是否确认删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            var id = row.id
            deleteuser(id).then(response => {
              const data = response.data
              console.log(data)
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              var data_len = this.tableData.length
              var is_jump = false
              if (data_len === 1) {
                is_jump = true
              } else {
                is_jump = false
              }
              if (this.current_page === 1) {
                this.getuserinfo(this.current_page, '', this.page_size)
              } else {
                if (is_jump) {
                  this.getuserinfo(this.current_page - 1, '', this.page_size)
                } else {
                  this.getuserinfo(this.current_page, '', this.page_size)
                }
              }
            }).catch(error => {
              console.log(error)
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
        },
        submitForm(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              var date = this.ruleForm.birthday
              // var date_str = date.toLocaleDateString()
              // var date_list = date_str.split('/')
              // var birthday = date_list[0] + '-' + date_list[1] + '-' + date_list[2]
              // date = new Date(date + this.timezoneOffset)
              // date = date.toJSON().replace("T"," ").replace("Z","")
              // date = new Date(date)
              if( typeof(date) == 'object') {
                // console.log(date)
                // var tmp_date = date.toJSON().replace("T"," ").replace("Z","")
                // console.log(tmp_date)
                // this.ruleForm.birthday = new Date(tmp_date + this.timezoneOffset).toISOString().split("T")[0]
                // console.log(this.ruleForm.birthday)

                // this.ruleForm.birthday = date.toLocaleDateString().replace(/\//g,'-')
                this.ruleForm.birthday = datetime.format(date,"YYYY-MM-DD")
              } else {
                // string
                this.ruleForm.birthday = date
              }
              this.ruleForm.group_id = this.ruleForm.group
              this.ruleForm.gender = String(this.ruleForm.gender)
              this.ruleForm.status = String(this.ruleForm.status)
              console.log(this.ruleForm)
              if (this.use === 1) {
                // if (this.ruleForm.password === '') {
                //   this.ruleForm.password = 'none'
                // }
                patchuser(this.ruleForm).then(response => {
                  const data = response.data
                  console.log(data)
                  this.$message({
                    message: '编辑用户成功！',
                    type: 'success'
                  })
                  this.dialogFormVisible = false
                  this.fileList = []
                  this.$refs[formName].resetFields()
                  this.getuserinfo(this.current_page, '', this.page_size)
                }).catch(error => {
                  console.log(error)
                  /* var date_str = this.ruleForm.birthday
                  console.log(date_str)
                  var new_date_str = date_str.replace(/-/g, '/')
                  var newdate = new Date(new_date_str)
                  console.log(newdate)
                  this.ruleForm.birthday =  newdate */
                })
              } else {
                console.log(this.ruleForm.image_url)
                postuser(this.ruleForm).then(response => {
                  const data = response.data
                  console.log(data)
                  this.$message({
                    message: '新增用户成功！',
                    type: 'success'
                  })
                  this.$refs[formName].resetFields()
                  this.dialogFormVisible = false
                  this.fileList = []
                  this.getuserinfo(this.current_page, '', this.page_size)
                }).catch(error => {
                  console.log(error)
                  /*
                  var date_str = this.ruleForm.birthday
                  console.log(date_str)
                  var new_date_str = date_str.replace(/-/g, '/')
                  var newdate = new Date(new_date_str)
                  console.log(newdate)
                  this.ruleForm.birthday =  newdate
                  */
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        },
        resetForm(formName) {
          this.$message({
            type: 'info',
            message: '取消输入'
          })
          this.dialogFormVisible = false
          // this.$refs[formName].resetFields()
          this.clearFormdata()
          this.fileList = []
        },
        currentChange(val) {
          this.current_page = val
          console.log(this.current_page)
          this.getuserinfo(this.current_page, this.searchuser, this.page_size)
        },
        sizeChange(val) {
          console.log(val)
          var page_count = this.total / val
          var max_pae = Math.ceil(page_count)
          this.page_size = val
          if (this.current_page <= max_pae) {
            this.getuserinfo(this.current_page, this.searchuser, this.page_size)
          } else {
            this.getuserinfo(max_pae, this.searchuser, this.page_size)
          }
        },
        dialogcolse() {
          // 对话框关闭的回调
          // this.$refs['ruleForm'].resetFields()
          this.clearFormdata()
        },
        handleRemove(file, fileList) {
          console.log(file, fileList)
        },
        handlePreview(file) {
          console.log(file)
        },
        handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
        },
        beforeRemove(file, fileList) {
          return this.$confirm(`确定移除 ${file.name}？`)
        },
        handlesuccess(file) {
          this.ruleForm.image_url = file.data.image_url
          console.log('回调，返回上传成功的文件名')
        }
      },
      created: function() {
        var offset = new Date().getTimezoneOffset() / 60
        if (offset >= 0){
          this.timezoneOffset = '+' + offset.toString()
        } else {
          this.timezoneOffset = offset.toString()
        }
        this.timeoffset = new Date('1990-01-01 00:00:00' + this.timezoneOffset).toJSON().split('.')[0].split('T')[1] // GMT +8 为 08:00:00
        console.log(this.timezoneOffset)
        console.log(this.timeoffset)
        this.upload_url = process.env.BASE_API + '/admin/file'
        // 获取所有用户信息
        this.getuserinfo(this.current_page, '', this.page_size)
        // 获取所有用户组信息
        this.getgroupinfo()
        // getuser().then(response => {
        //   // const data = response.data
        //   this.total = response.data_count
        // }).catch(error => {
        //   console.log(error)
        // })
      }
    }
</script>

<style scoped>

</style>
